$(function(){

    //低版本IE placeholder的问题
    $('input[placeholder]').placeholder({isUseSpan:true});
    $('textarea[placeholder]').placeholder({isUseSpan:true});

	/*body高度*/
	(function(){
		set_height();
	})();

    /**
     * 根据窗口自动调整高度
     */
	function set_height(){
		var bodyHeight = $('body').height();
		setBodyHeight(bodyHeight);
		$(window).resize(function(){
			setBodyHeight(bodyHeight);
		});
	}

    /**
     * 设置窗口高度
     * @param bodyHeight
     */
	function setBodyHeight(bodyHeight){
		if(bodyHeight < $(window).height()){
			$('body').height($(window).height());
		}else{
			$('body').height('auto');
		}
	}
	
	/*选中第一个输入框*/
	$('form').find('input.form_control').eq(0).focus();
	
	/*清空表单*/
	$("#feedback_form")[0].reset();
	$('#js_file_path').val('');
	$('#upload_file').on('click', function(){
		$(this).blur();
	});

    //对内容进行处理
	$('#js_content').on({
        //截取500字以内的文字
		'keyup': function(){
			var val = $(this).val();
			if(val.length > 500){
				$(this).val(val.substr(0, 500));
			}
		}
	});

    //清空提示
	$('.blue_btn').click(function(){
		$('.submit-success').remove();
		$('.submit-error').remove();
	});

    //表单检测
	$("#feedback_form").validate({
        debug: true,
		rules: {
			content : {
				maxlength:500,
                required: true
			},
			qq : {
                number: true,
                minlength: 4,
                maxlength: 10,
                required: {
					depends:function(){
						return ($(this).val().length <= 0 && $('input[name=email]').val().length <= 0);
					}
				}
			},
			email:{
                email: true,
				required: {
					depends:function(){
						return ($(this).val().length <= 0 && $('input[name=qq]').val().length <= 0);
					}
				}
			}
		},
		messages:{
			qq:{
                number: "QQ号码格式错误",
                minlength: "QQ号码不可小于4位",
                maxlength: "QQ号码不可大于10位",
				required:"请填写您的QQ号码"
			},
			email:{
                email: "邮箱格式不正确",
				required:"请填写您的邮箱"
			},
			content : {
				maxlength: "500字以内",
                required:"正文为必填项"
			}
		},
		errorPlacement:function(error, element){
			element.parent().find("label.checked").remove();
			if(element.attr('id') == 'qq'){
                //隐藏QQ右侧提示
				$('.qqbox strong').hide();
			}
			if(element.attr('id') == 'js_content'){
				error.insertAfter(element.parent());
			} else {
				error.appendTo(element.parent());
			}
		},
		success: function(label) {
			label.html('').attr('class', 'checked');
		},
		submitHandler: function(){

		}
	});

    //提交
	$("#feedback_form").find('.blue_btn').on('click', function(){
		if ($("#feedback_form").valid()){
			submitOn();
		}
		return false;
	});

    //触发提交
	function submitOn(){
		//console.log($('#feedback_form').serializeArray());return;
		$('.blue_btn').attr("disabled",true).html('正在提交…');
		$.ajax({
			type: 'post',
			url: '/feedback/add',
			data: $('#feedback_form').serializeArray(),
            dataType: 'json',
			success: function(data){
				$('.blue_btn').attr("disabled",false).html('提交');
				if (data){
					$('.submit-success').remove();
					$('.submitbox').append('<label class="submit-success success"></label>');
					$("#feedback_form")[0].reset();
					//t = setTimeout(function(){
					//	clearTimeout(t);
					//	window.opener = null;
                     //   window.open('','_self');
                     //   window.close();
					//	window.location.reload(); //如果无法关闭浏览器刷新一下页面
					//}, 3000);
					$("#js_imglist").empty();
				} else {
					$('.submit-error').remove();
					$('.submitbox').append('<label class="submit-error error">提交失败！</label>');
				}
			}
		});
	}

    //QQ右侧提示
	$('#qq').on('blur', function(){
		if($('.qqbox .error').size() == 0 || $('.qqbox').find('.error:hidden').size() == 1){
			$('.qqbox strong').show();
		}
		
	});
	
	/*上传截图*/
	$('#upload_file').hover(function(){
		$('#js_tips').show();
	}, function(){
		$('#js_tips').hide();
	});

	(function(){
		var count = 1;
        //上传图片不可超过4张
		$('#upload_file').on('click', function(){
			if (count < 5) {
				$('#upload_file').val('');
			} else {
				count = 5;
				return false;
			}
		});

		//删除已经上传的文件
		$('#js_imglist').on('click', '.delete', function(){
			$("#js_imglist_error").html("");
			/*var $this_upload_info = $(this).parents('.upload_info');
            //点中的文件索引
			var index = $this_upload_info.index();
			var file_path_val = $('#js_file_path').val();
            //拆分路径字符串
			var file_path_array = file_path_val.split('|');
            var file_path = file_path_array.splice(index, 1); //删除指定位置的值
			var str = '';
            if (file_path_array.length > 0) {
                str += file_path_array.join('|');
            }*/
			//发送后台去删除这个文件
			var me=$(this);
			var fpath = me.next().val();
			if(!fpath)
			{
				me.parent().remove();
			}
			else
			{
				me.text("删除中...").attr("disabled",true);
				$.ajax({
					type: 'post',
					url: '/feedback/detele_img',
					data: {'file_name' : fpath},
					dataType: 'json',
					success: function(data){
						me.text("删除").attr("disabled",false);
						if (data.error_code == 0){
							me.parent().remove();
							/*$('#js_file_path').val(str);
							 count--;
							 if (count == 4){
							 $('#js_uploadbtn').parent().removeClass('upload_active');
							 }*/
						} else {
							alert('删除失败！');
						}
					}
				});
			}

		});
		var Uploader = new plupload.Uploader({
				runtimes: 'html5,flash,html4',
				browse_button: "upload_file", // you can pass in id...
				url: '/feedback/upload_img',
				flash_swf_url: '/static/js/jquery/plupload/Moxie.swf',
				silverlight_xap_url: '/static/js/jquery/plupload/Moxie.xap',
				drop_element: "body",
				headers: {"x-csrf-token": $.cookie("__CSRF__") || ""},
				max_file_size: '2mb',
				//chunk_size: '4mb',
				filters: {
					mime_types: [
						{title: "图像文件（.jpg,.gif,.png）", extensions: "jpg,gif,png"}
					]
				},
				init:{
					FilesAdded: function(up, files){
						var size = $('#js_imglist .uploading,#js_imglist .success').size();
						if(size<=5 && size+files.length<=5)
						{
							$.each(files,function(k,file){
								$('#js_imglist').append('<p class="upload_info" id="'+file.id+'"><i></i><strong>'+file.name+'</strong><span class="status uploading" style="padding:0 5px;color:#4b4b4b;">上传中...</span><button class="delete" data-fname="'+file.name+'">删除</button><input type="hidden" class="file_value"><label class="error" style="display: inline-block;padding:0 10px;"></label></p>');
							});
						}
						if(size>5 || size+files.length>5)
						{
							if(size>5)$("#upload_file").attr("disabled",true);
							$("#js_imglist_error").html("最多只能上传5张图片");
							up.stop();
							return false;
						}
						else
						{
							$("#upload_file").attr("disabled",false);
							$("#js_imglist_error").html("");
						}
						if(up.state==1)
						{
							up.start();
						}
					},
					FileUploaded:function(uploader,file,responseObject){
						$("#js_imglist_error").html();
						var result = eval("("+responseObject.response+")");
						var f = $("#"+file.id);
						if(! result.error_code) {
							f.find(".file_value").attr({"name":"file_path[]","value":result.file_path});
							f.find(".status").removeClass("uploading").addClass("success").html("(√)");
						}
						else
						{
							f.find(".status").removeClass("uploading").addClass("failed").html("(×)");
							f.find(".error").html(result.message);
						}
						/*if(! result.error_code){

							$('#js_imglist').find('label.error').remove();
							$('#js_imglist').append('<p class="upload_info"><i></i><strong>'+result.file_name+'</strong><span class="delete">删除</span></p>');
							var val = $('#js_file_path').val();
							//添加文件路径的值，使用|来分割
							if(val != ''){
								val += '|' + result.file_path;
							}else {
								val = result.file_path;
							}
							$('#js_file_path').val(val);
							count++;
							//禁止再上传
							if(count == 5){
								$('#js_uploadbtn').parent().addClass('upload_active');
							}
							set_height();
						} else {
							$.each(files,function(k,file){

							});
						}*/
					},
					Error:function(up, err){
						var file = err.file;
						var error = "上传失败，请稍后重试";
						if(err.code==-601)
						{
							error = "文件格式错误，截图支持格式：jpg、png、gif";
						}
						else if(err.code==-600)
						{
							error = "文件大小不能超过2MB";
						}
						$('#js_imglist').append('<p class="upload_info" id="'+file.id+'"><i></i><strong>'+file.name+'</strong><span class="status failed" style="padding:0 5px;color:#4b4b4b;">(×)</span><button class="delete" data-fname="'+file.name+'">删除</button><input type="hidden" class="file_value"><label class="error" style="display: inline-block;padding:0 10px;">'+error+'</label></p>');

					}
				}
			}
		);
		Uploader.init();
		//console.log(Uploader);
        //上传图片
		/*$('#upload_file').on('change', function(){
            //上传图片ajax
			$('#feedback_form').ajaxSubmit({
				url: '/feedback/upload_img',
				dataType: 'json',
				success: function(result){
                    //如果本身未存在错误信息则修改，否则新增
					if(! result.error_code){
						$('#js_imglist').find('label.error').remove();
						$('#js_imglist').append('<p class="upload_info"><i></i><strong>'+result.file_name+'</strong><span class="delete">删除</span></p>');
						var val = $('#js_file_path').val();
                        //添加文件路径的值，使用|来分割
						if(val != ''){
							val += '|' + result.file_path;
						}else {
							val = result.file_path;
						}
						$('#js_file_path').val(val);
						count++;
                        //禁止再上传
						if(count == 5){
							$('#js_uploadbtn').parent().addClass('upload_active');
						}
						set_height();
					} else {
						if ($('#js_imglist').find('label.error').size() == 0){
							$('#js_imglist').append('<label class="error">' + result.message + '</label>');
						} else {
							$('#js_imglist').find('label.error').html(result.message);
						}
					}
				},
				error : function(XMLHttpRequest){
                    //文件超出
					if (XMLHttpRequest.status == 413) {
						var msg = '文件大小不能超过2MB';
						if ($('#js_imglist').find('label.error').size() == 0){
							$('#js_imglist').append('<label class="error">' + msg + '</label>');
						} else {
							$('#js_imglist').find('label.error').html(msg);
						}
					}
				}
			});
		});*/
	})();

});